package com.hang.gymmanager.util;

import cn.hutool.jwt.JWTUtil;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import static com.hang.gymmanager.Enum.CommonConstant.GYM_HEADER;

/**
 * @author wyq
 * @version v1.0.0
 * @explain
 * @date 2024/3/19 18:51
 */
public class SecurityUtils {

    /**
     * 获取用户id
     * @return
     */
    public static Integer getUserId(){
        HttpServletRequest request = getRequest();
        String token = request.getHeader(GYM_HEADER);
        if(token==null){
            return null;
        }
        token = token.replaceFirst("(?i)Bearer", "").trim();
        Integer userId = JWTUtil.parseToken(token).getPayloads().getInt("userId");
        if(userId==null){
            return -2;
        }
        return userId;
    }

    /**
     * 获取 HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return (requestAttributes == null) ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
    }

}
